package com.jml.jdk8.函数方法;

import java.util.Optional;

/**
 * @Author: J
 * @DATE: 2022-04-15 14:51
 */
public class OptionalTest {

    public static void main(String[] args) {
        //Optional<Object> empty = Optional.empty();
        //orElseGet();
        map();
    }

    private static void map() {
        User user = new User();
        Optional<User> optional = Optional.ofNullable(user);
        Optional<Integer> integer = optional.map(x -> x.getId());
        Integer aa = integer.orElseGet(() -> {
            throw new RuntimeException("");
        });
        System.out.println(aa);
    }

    public static void orElseGet() {
        //Optional<String> s = Optional.of("123");
        Optional<String> s = Optional.empty();
        String s1 = s.orElseGet(() -> {
            return "nihao";
        });
        System.out.println(s1);
        System.out.println(s.get());
    }


    public void orElse() {
        Optional<String> optional1 = Optional.empty();
        //orElse方法，参数是泛型，
        //如果optional里面没有值就返回备用的值other
        String other = optional1.orElse("other");
        System.out.println(other);
    }

    public void ifPresent() {
        Optional<String> s = Optional.of("123");
        s.ifPresent(a -> System.out.println(a + "zzz"));
        System.out.println(s.get());
        User user = new User();
        user.setId(10);
        Optional<User> s1 = Optional.of(user);
        s1.ifPresent(a -> a.setId(222));
        System.out.println(s1.get().getId());
    }
}
